package com.hdp.jetpack_mvvm.livedata

import android.util.Log
import androidx.lifecycle.*

class ViewModel1 : ViewModel() {
    val TAG = "ViewModel1"
    private val name = MutableLiveData<String>()
    private val pwd = MutableLiveData<String>()
    private val canSubmit = MediatorLiveData<Boolean>()

    init {
        canSubmit.addSource(getName()) {
            canSubmit.value = updateCanSubmit()
        }
        canSubmit.addSource(getPwd()) {
            canSubmit.value = updateCanSubmit()
        }
    }

    private fun updateCanSubmit(): Boolean {
        return name.value?.isNotEmpty() ?: false && pwd.value?.isNotEmpty() ?: false
    }

    public fun setName(name: String) {
        this.name.value = name
    }

    fun setPwd(pwd: String) {
        this.pwd.value = pwd
    }

    fun getName(): LiveData<String> {
        return this.name
    }

    fun getPwd(): LiveData<String> {
        return this.pwd;
    }

    fun getCanSubmit(): LiveData<Boolean> {
        return this.canSubmit
    }

    fun loadName() {
        setName("张三")
    }

    fun loadName2() {
        setName("张三2")
    }

    fun loadPwd() {
        setPwd("123456")
    }

    fun loadData() {
        setName("张三")
        setPwd("123456")
    }

    override fun onCleared() {
        super.onCleared()
        Log.e(TAG, this.toString() + "_onCleared")
    }
}